#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/wait.h>
#include<pthread.h>
#include<unistd.h>
#include<fcntl.h>
#include<signal.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<arpa/inet.h>
#include<signal.h>
#include<ctype.h>
//使用多进程技术实现服务器的并发
#define SERVICE_PROT 9527
void catch_child(int signum){
   while((wait(NULL))>0);
}
void  sys_error(const char*s){
     perror(s);
     exit(-1);
}
int main(){
  int sfd,sfd1;
  pid_t pid;
  struct sockaddr_in saddr,caddr;
  char buf[1024];
  saddr.sin_family=AF_INET;
  saddr.sin_port=htons(SERVICE_PROT);
  saddr.sin_addr.s_addr=htonl(INADDR_ANY);
  sfd=socket(AF_INET,SOCK_STREAM,0);
  if(sfd==-1){
     sys_error("socket is error");    
  }
  int ret=bind(sfd,(struct sockaddr*)&saddr,sizeof(saddr));
  listen(sfd,128);
  socklen_t caddr_len=sizeof(caddr);
  while(1){
     sfd1=accept(sfd,(struct sockaddr*)&caddr,&caddr_len);
     pid=fork();//创建进程
     if(pid==-1){
         sys_error("fork is error");
     }
     else if(pid==0){//子进程
        close(sfd);
        break;
     }else{//利用父进程回收子进程
        struct sigaction act;
	sigemptyset(&act.sa_mask);
	act.sa_flags=0;
	act.sa_handler=catch_child;
        ret=sigaction(SIGCHLD,&act,NULL);//注册信号捕捉函数
	if(ret==-1){
	   sys_error("sigaction is error");
	}
     }
  }
  if(pid==0){ 
     while(1){
        ret=read(sfd1,buf,sizeof(buf));
	write(STDOUT_FILENO,buf,ret);
	int i=0;
	for(;i<ret;i++){
           buf[i]=toupper(buf[i]);              
        }
        write(sfd1,buf,ret); 
     }
  }
   return 0;
}
